package org.upo.eps.it.phama.struts.action;

import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.upo.eps.it.phama.bean.Empleado;
import org.upo.eps.it.phama.dao.EmpleadoDAO;
import org.upo.eps.it.phama.struts.actionform.LoginActionForm;
import org.upo.eps.it.phama.util.Utils;

/**
 *
 * @author grupo 4
 */
public class LoginAction extends Action {

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        HttpSession session = request.getSession();
        String result = "login";
        /* Si se ha pasado la validación efectuada por el ActionForm asociado, se procede a verificar
         * la identidad del usuario. Si la misma NO fuera correcta, se agrega un error a la colección
         * de errores del citado ActionForm.
         */

        LoginActionForm af = (LoginActionForm) form;
        ActionErrors errors = af.getErrors();
        if (af.getUser() != null && af.getPassword() != null) {
            try {
                Empleado usuario = EmpleadoDAO.getByUsername(af.getUser(), Utils.getMd5(af.getPassword()));
                if (usuario != null) {
                    session.setAttribute("user", usuario);
                    session.setAttribute("tipo", usuario.getCategoria());
                    result = "menu";
                } else {
                    errors.add("invalido", new ActionMessage("error.invaliduser"));
                }
            } catch (NoSuchAlgorithmException ex) {
                errors.add("error", new ActionMessage("error.excepcion"));
                Logger.getLogger(LoginActionForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        /* Si se ha producido un error (el único posible es porque el usuario/contraseña no sean correctos)
         * se graba el mismo en el request original y se vuelve a lanzar.
         */
        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            return (new ActionForward(mapping.getInput())); 
        } else {
            return mapping.findForward(result);
        }
    }
}
